﻿using System;
using Volo.Abp.Validation.StringValues;

namespace Xms.Abp.Validation.StringValues;

[Serializable]
[ValueValidator("DATE")]
public class DateValueValidator : ValueValidatorBase
{
    public Date MinValue
    {
        get => (this["MinValue"] ?? Date.Parse("0001-01-01")).To<Date>();
        set => this["MinValue"] = value;
    }

    public Date MaxValue
    {
        get => (this["MaxValue"] ?? Date.Parse("9999-12-31")).To<Date>();
        set => this["MaxValue"] = value;
    }

    public DateValueValidator()
    {
        MinValue = Date.MinValue;
        MaxValue = Date.MaxValue;
    }

    public DateValueValidator(Date? minValue = null, Date? maxValue = null)
    {
        MinValue = minValue ?? Date.MinValue;
        MaxValue = maxValue ?? Date.MaxValue;
        if (MinValue > MaxValue)
        {
            throw new ArgumentException("Parameter 'minValue' cannot be less than parameter 'maxValue'.");
        }
    }

    public override bool IsValid(object value)
    {
        if (value == null)
        {
            return false;
        }

        if (value is Date date)
        {
            return IsValidInternal(date);
        }

        if (value is string str)
        {
            if (Date.TryParse(str, out var dateValue))
            {
                return IsValidInternal(dateValue);
            }
        }

        return false;
    }

    protected virtual bool IsValidInternal(Date value)
    {
        return value.IsBetween(MinValue, MaxValue);
    }
}